package com.tan.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

//工具类sqlSessionFactory -->sqlSession
public class MybatisUtils {
    //提升作用域
    private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            //创建mybatis的工厂，初始化mybatis的配置。
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //SqlSessionFactory创建的SqlSession实例，这个实例有更新SQL数据库的所有方法。
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
        /*SqlSession sqlSession = sqlSessionFactory.openSession();
        return sqlSession;*/
    }
}
